<template>
    <v-dialog :model-value="visible" max-width="800px" persistent @update:model-value="$emit('update:visible', $event)">
        <v-card>
            <v-card-title>
                <span>{{ title }}</span>
            </v-card-title>
            <v-card-text>
                <v-form ref="formRef" v-model="valid" class="menuManagement-edit-container">
                    <v-row>
                        <!-- 上级菜单 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :model-value="parentMenuName"
                                append-inner-icon="mdi-magnify"
                                label="上级菜单"
                                readonly
                                @click="onShowParentMenu"
                            ></v-text-field>
                            <v-btn
                                :disabled="formStatus && edenOldParentId"
                                class="input-btn-choose"
                                color="primary"
                                icon
                                style="margin-top: -48px; margin-left: 220px"
                                @click="onShowParentMenu"
                            >
                                <v-icon>mdi-magnify</v-icon>
                            </v-btn>
                        </v-col>
                        <!-- 名称 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :model-value="localForm.menuName"
                                :rules="[(v: string) => !!v || '请输入名称']"
                                label="名称"
                                required
                                @update:model-value="updateForm('menuName', $event)"
                            ></v-text-field>
                        </v-col>
                        <!-- 类型 -->
                        <v-col cols="12" md="6">
                            <v-select
                                :items="menuTypeOptions"
                                :model-value="localForm.type"
                                :rules="[(v: string) => !!v || '请选择类型']"
                                item-title="dictName"
                                item-value="dictValue"
                                label="类型"
                                required
                                @update:model-value="
                                    (val: string) => {
                                        updateForm('type', val);
                                        onMenuTypeChange(val);
                                    }
                                "
                            ></v-select>
                        </v-col>
                        <!-- 权限 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :disabled="localForm.type != '2'"
                                :model-value="localForm.permissions"
                                hint="对应后端 @RequiresPermissions('xxx')"
                                label="权限"
                                persistent-hint
                                @update:model-value="updateForm('permissions', $event)"
                            ></v-text-field>
                        </v-col>
                        <!-- 排序 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :max="500"
                                :model-value="localForm.sortNo"
                                :rules="[(v: any) => !!v || '请输入排序']"
                                label="排序"
                                required
                                type="number"
                                @update:model-value="updateForm('sortNo', $event)"
                            ></v-text-field>
                        </v-col>
                        <!-- 隐藏 -->
                        <v-col cols="12" md="6">
                            <v-select
                                :disabled="!(localForm.type === '1' || localForm.type === '3')"
                                :items="noYesOptions"
                                :model-value="localForm.hidden"
                                :rules="[(v: string) => !!v || '请选择是否隐藏']"
                                item-title="dictName"
                                item-value="dictValue"
                                label="隐藏"
                                required
                                @update:model-value="updateForm('hidden', $event)"
                            ></v-select>
                        </v-col>
                        <!-- 总是显示 -->
                        <v-col cols="12" md="6">
                            <v-select
                                :disabled="localForm.type !== '1'"
                                :items="noYesOptions"
                                :model-value="localForm.alwaysShow"
                                :rules="[(v: string) => !!v || '请选择是否总是显示']"
                                item-title="dictName"
                                item-value="dictValue"
                                label="总是显示"
                                required
                                @update:model-value="updateForm('alwaysShow', $event)"
                            ></v-select>
                        </v-col>
                        <!-- 路径 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :disabled="!(localForm.type === '1' || localForm.type === '3')"
                                :model-value="localForm.url"
                                hint="路由路径，支持动态路由参数"
                                label="路径"
                                persistent-hint
                                placeholder="请输入路径，如：/system/user"
                                @update:model-value="updateForm('url', $event)"
                            ></v-text-field>
                        </v-col>
                        <!-- 组件路径 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :disabled="localForm.type !== '1'"
                                :model-value="localForm.component"
                                hint="Vue组件的文件路径"
                                label="组件路径"
                                persistent-hint
                                placeholder="请输入组件路径，如：/views/system/UserManagement.vue"
                                @update:model-value="updateForm('component', $event)"
                            ></v-text-field>
                        </v-col>
                        <!-- 重定向 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :disabled="localForm.type !== '1'"
                                :model-value="localForm.redirect"
                                label="重定向"
                                @update:model-value="updateForm('redirect', $event)"
                            ></v-text-field>
                        </v-col>
                        <!-- 图标 -->
                        <v-col cols="12" md="6">
                            <v-text-field
                                :disabled="!(localForm.type === '1' || localForm.type === '3')"
                                :model-value="localForm.icon"
                                append-inner-icon="mdi-magnify"
                                label="图标"
                                readonly
                                @update:model-value="updateForm('icon', $event)"
                                @click:append-inner="showIconDialog"
                            >
                                <template v-slot:prepend-inner>
                                    <v-icon v-if="localForm.icon" :icon="localForm.icon" class="mr-2" color="primary"></v-icon>
                                    <v-icon v-else class="mr-2" color="grey" icon="mdi-image-outline"></v-icon>
                                </template>
                            </v-text-field>
                        </v-col>
                        <!-- 标签 -->
                        <v-col cols="12" md="6">
                            <v-select
                                :items="labelOptions"
                                :model-value="localForm.label"
                                :rules="[(v: any) => (v && v.length > 0) || '请选择标签']"
                                item-title="dictName"
                                item-value="dictValue"
                                label="标签"
                                multiple
                                required
                                @update:model-value="updateForm('label', $event)"
                            ></v-select>
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>
            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn @click="onCancel">取消</v-btn>
                <v-btn :loading="saving" color="primary" @click="onSave">保存</v-btn>
            </v-card-actions>
        </v-card>

        <!-- 图标选择器 -->
        <IconPicker
            v-model:visible="iconPickerVisible"
            :model-value="selectedIcon"
            @confirm="onIconSelected"
            @update:model-value="onIconSelected"
        />
    </v-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue';
import IconPicker from '@/components/IconPicker.vue';
import { doInsert, doUpdate } from '@/api/system/menu/menuManagement';
import { useMessage } from '@/composables/useMessage';
import { isNull } from '@/utils/validate';
import { deepClone } from '@/utils/clone';

interface MenuFormType {
    id?: string;
    menuName: string;
    type: string;
    permissions?: string;
    sortNo: number;
    hidden: string;
    alwaysShow: string;
    url?: string;
    component?: string;
    redirect?: string;
    icon?: string;
    label?: string[];
    parentId?: string;
    version?: number;
}

const props = defineProps({
    visible: Boolean,
    title: String,
    form: {
        type: Object as () => MenuFormType,
        default: () => ({})
    },
    parentMenuName: String,
    formStatus: Boolean,
    edenOldParentId: String,
    menuTypeOptions: {
        type: Array,
        default: () => []
    },
    noYesOptions: {
        type: Array,
        default: () => []
    },
    labelOptions: {
        type: Array,
        default: () => []
    }
});

const emit = defineEmits(['update:visible', 'save', 'cancel', 'showParentMenu', 'menuTypeChange', 'update:form']);

// 创建本地响应式表单数据
const localForm = ref<MenuFormType>({ ...props.form });

// 监听 props.form 的变化，同步到本地表单
watch(
    () => props.form,
    (newForm) => {
        localForm.value = { ...newForm };
    },
    { deep: true, immediate: true }
);

const { success: showSuccess, error: showError } = useMessage();

const valid = ref(true);
const formRef = ref();
const saving = ref(false);

// 图标选择器相关
const iconPickerVisible = ref(false);
const selectedIcon = ref(props.form.icon || '');

// 监听本地表单图标变化
watch(
    () => localForm.value.icon,
    (newIcon) => {
        selectedIcon.value = newIcon || '';
    }
);

const updateForm = (field: keyof MenuFormType, value: any) => {
    // 更新本地表单数据
    localForm.value = { ...localForm.value, [field]: value };
    // 通知父组件更新
    emit('update:form', localForm.value);
};

const onShowParentMenu = () => emit('showParentMenu');

const showIconDialog = () => {
    selectedIcon.value = localForm.value.icon || '';
    iconPickerVisible.value = true;
};

const onIconSelected = (icon: string) => {
    console.log('图标选择器选中图标:', icon);
    selectedIcon.value = icon;
    updateForm('icon', icon);
    console.log('更新表单图标后 localForm.icon:', localForm.value.icon);
    // 关闭图标选择器
    iconPickerVisible.value = false;
};

const onMenuTypeChange = (val: string) => {
    // 根据菜单类型清空相关字段
    const menuType = '1';
    const buttonType = '2';
    const outreachType = '3';

    if (menuType === val) {
        // 菜单类型
        updateForm('permissions', '');
    } else if (buttonType === val) {
        // 按钮类型
        updateForm('url', '');
        updateForm('component', '');
        updateForm('redirect', '');
        updateForm('icon', '');
        updateForm('alwaysShow', '0');
        updateForm('hidden', '0');
    } else if (outreachType === val) {
        // 外链类型
        updateForm('component', '');
        updateForm('redirect', '');
        updateForm('permissions', '');
    }

    emit('menuTypeChange', val);
};

const onCancel = () => emit('cancel');

const onSave = async () => {
    if (!formRef.value) return;

    const { valid: isValid } = await formRef.value.validate();
    if (!isValid) return;

    saving.value = true;

    try {
        // 使用本地表单数据
        let tmpForm = deepClone(localForm.value);

        // 确保使用最新的图标值
        if (selectedIcon.value) {
            tmpForm.icon = selectedIcon.value;
        }

        // 添加调试日志
        console.log('保存前的表单数据:', tmpForm);
        console.log('当前选中的图标:', selectedIcon.value);
        console.log('localForm.icon:', localForm.value.icon);

        // 处理标签 - 将数组转换为逗号分隔的字符串
        if (tmpForm.label && Array.isArray(tmpForm.label)) {
            (tmpForm as any).label = tmpForm.label.join(',');
        }

        let response;
        if (!isNull(tmpForm.id)) {
            // 更新
            response = await doUpdate(tmpForm);
        } else {
            // 新增
            response = await doInsert(tmpForm);
        }

        showSuccess(response.data?.msg || '保存成功');
        emit('save', tmpForm);
    } catch (error) {
        console.error('保存失败:', error);
        showError('保存失败');
    } finally {
        saving.value = false;
    }
};
</script>

<style scoped>
.menuManagement-edit-container {
    padding: 10px 0;
}

.input-btn-choose {
    position: absolute;
    right: 10px;
    top: 32px;
    z-index: 2;
}
</style>
